package com.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.mapper.StudentMapper;
import com.demo.pojo.entity.Student;
import com.demo.pojo.dto.StudentListDTO;
import com.demo.service.StudentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学生服务实现类
 */
@Service
public class StudentServiceImpl implements StudentService {
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Override
    public IPage<StudentListDTO> getStudentList(Page<Student> page, Long stuNo, String stuName, Integer stuSex, String stuPhone) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();

        // 学号：-1 或 null 忽略
        if (stuNo != null && stuNo > 0) {
            queryWrapper.eq("stu_no", stuNo);
        }

        // 姓名：非空模糊
        if (StringUtils.hasText(stuName)) {
            queryWrapper.like("stu_name", stuName);
        }

        // 性别：-1 或 null 忽略
        if (stuSex != null && (stuSex == 0 || stuSex == 1)) {
            queryWrapper.eq("stu_sex", stuSex);
        }

        // 手机：非空模糊或等值，通常用 like
        if (StringUtils.hasText(stuPhone)) {
            queryWrapper.like("stu_phone", stuPhone);
        }

        // 按学号升序排列
        queryWrapper.orderByAsc("stu_no");

        IPage<Student> studentPage = studentMapper.selectPage(page, queryWrapper);

        IPage<StudentListDTO> dtoPage = new Page<>();
        BeanUtils.copyProperties(studentPage, dtoPage);

        List<StudentListDTO> dtoList = studentPage.getRecords().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        dtoPage.setRecords(dtoList);

        return dtoPage;
    }
    
    @Override
    public Student getStudentById(Integer id) {
        return studentMapper.selectById(id);
    }
    
    @Override
    public Student getStudentByNo(Long stuNo) {
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stu_no", stuNo);
        return studentMapper.selectOne(queryWrapper);
    }
    
    @Override
    public boolean addStudent(Student student) {
        // 检查学号是否已存在
        if (getStudentByNo(student.getStuNo()) != null) {
            throw new RuntimeException("学号已存在");
        }
        
        // 设置创建时间
        student.setStuUpdateDate(new Date());
        
        return studentMapper.insert(student) > 0;
    }
    
    @Override
    public boolean updateStudent(Student student) {
        // 检查学号是否被其他学生使用
        Student existingStudent = getStudentByNo(student.getStuNo());
        if (existingStudent != null && !existingStudent.getStudentId().equals(student.getStudentId())) {
            throw new RuntimeException("学号已被其他学生使用");
        }
        
        // 设置更新时间
        student.setStuUpdateDate(new Date());
        
        return studentMapper.updateById(student) > 0;
    }
    
    @Override
    public boolean deleteStudent(Integer id) {
        return studentMapper.deleteById(id) > 0;
    }
    
    @Override
    public boolean deleteStudents(List<Integer> ids) {
        return studentMapper.deleteBatchIds(ids) > 0;
    }
    
    /**
     * 将Student实体转换为StudentListDTO
     */
    private StudentListDTO convertToDTO(Student student) {
        StudentListDTO dto = new StudentListDTO();
        BeanUtils.copyProperties(student, dto);
        
        // 性别转换
        if (student.getStuSex() != null) {
            dto.setStuSexText(student.getStuSex() == 1 ? "男" : "女");
        }
        
        return dto;
    }

    @Override
    public Student login(Long stuNo, String idTail6) {
        QueryWrapper<Student> qw = new QueryWrapper<>();
        qw.eq("stu_no", stuNo);
        Student student = studentMapper.selectOne(qw);
        if (student == null) {
            throw new RuntimeException("学号不存在");
        }
        String idCard = student.getStuIdCard();
        if (idCard == null || idCard.length() < 6) {
            throw new RuntimeException("系统未配置身份证号");
        }
        String tail6 = idCard.substring(idCard.length() - 6);
        if (!tail6.equalsIgnoreCase(idTail6)) {
            throw new RuntimeException("身份证后六位不正确");
        }
        return student;
    }
}
